﻿using BBCore.Application.Extensions;
using BootstrapBlazor.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BBCore.Application
{
    public class DefaultDataService<TModel>(IFreeSql freeSql) : DataServiceBase<TModel> where TModel : class, new()
    {
        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public override async Task<bool> DeleteAsync(IEnumerable<TModel> models)
        {
            await freeSql.Delete<TModel>(models).ExecuteAffrowsAsync();
            return true;
        }

        /// <summary>
        /// 保存方法
        /// </summary>
        /// <param name="model"></param>
        /// <param name="changedType"></param>
        /// <returns></returns>
        public override async Task<bool> SaveAsync(TModel model, ItemChangedType changedType)
        {
            if (changedType == ItemChangedType.Add)
            {
                await freeSql.Insert<TModel>(model).ExecuteAffrowsAsync();
            }
            else if (changedType == ItemChangedType.Update)
            {
                await freeSql.Update<TModel>(model).ExecuteAffrowsAsync();
            }
            return true;
        }

        public override Task<QueryData<TModel>> QueryAsync(QueryPageOptions option) => Task.FromResult(new QueryData<TModel>
        {
            IsSorted = option.SortOrder != SortOrder.Unset,
            IsFiltered = option.Filters.Any(),
            IsAdvanceSearch = option.AdvanceSearches.Any(),
            IsSearch = option.Searches.Any() || option.CustomerSearches.Any(),
            Items = freeSql.Select<TModel>()
                           .WhereDynamicFilter(option.ToDynamicFilter())
                           .OrderByPropertyNameIf(option.SortOrder != SortOrder.Unset, option.SortName, option.SortOrder == SortOrder.Asc)
                           .Count(out var count)
                           .PageIf(option.PageIndex, option.PageItems, option.IsPage)
                           .ToList(),
            TotalCount = Convert.ToInt32(count)
        });
    }

}
